package com.carkeeper.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carkeeper.dto.CUserDTO;
import com.carkeeper.pojo.CUserPO;
import com.carkeeper.service.CUserService;
import com.carkeeper.vo.CUserQueryParamVo;
import com.carkeeper.vo.Pager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * c端用户控制器
 */
@RestController
@RequestMapping("/cuser")
public class CUserController {
    @Autowired
    private CUserService cUserService;

    /**
     * 获取C端用户分页数据
     *
     * @param paramVo 查询条件
     * @return 用户分页数据
     */
    @PostMapping("/page")
    public Pager<CUserPO> findByPage(@RequestBody CUserQueryParamVo paramVo) {
        Page<CUserPO> userPOPage = cUserService.findByPage(paramVo);
        //脱敏
        userPOPage.getRecords().forEach(po -> po.setPassword(null));
        return new Pager<>(userPOPage.getTotal(), userPOPage.getSize(), userPOPage.getPages(), userPOPage.getCurrent(), userPOPage.getRecords());
    }

    /**
     * 根据id获取C端用户详情
     *
     * @param id C端用户id
     * @return C端用户详情
     */
    @GetMapping("/{id}")
    public CUserDTO findById(@PathVariable Long id) {
        CUserDTO dto = new CUserDTO();
        CUserPO po = cUserService.findById(id);
        if (po != null) {
            BeanUtils.copyProperties(po, dto);
        }
        return dto;
    }

    /**
     * 删除C端用户
     *
     * @param id 用户id
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Long id) {
        return cUserService.delete(id);
    }

    /**
     * 获取C端用户列表
     *
     * @param queryDTO 查询条件
     * @return C端用户列表
     */
    @PostMapping("/list")
    public List<CUserDTO> findAll(@RequestBody CUserDTO queryDTO) {
        List<CUserPO> cUserPOList = cUserService.list(queryDTO);
        return cUserPOList.stream().map(po -> {
            CUserDTO dto = new CUserDTO();
            BeanUtils.copyProperties(po, dto);
            dto.setPassword(null);
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 新增C端用户
     *
     * @param po 用户信息
     * @return 操作结果
     */
    @PostMapping
    public Boolean save(@RequestBody CUserPO po) {
        return cUserService.saveAndUpdate(po);
    }

    /**
     * 更新C端用户信息
     *
     * @param id C端用户ID
     * @param po C端用户信息
     * @return 操作结果
     */
    @PutMapping("/{id}")
    public Boolean update(@PathVariable Long id, @RequestBody CUserPO po) {
        po.setId(id);
        return cUserService.saveAndUpdate(po);
    }
}
